'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/auto_run/pub/test 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		
		// 业务逻辑开始-----------------------------------------------------------
		//计算版权方佣金开始==============================
		//版权方
		var time = vk.pubfn.getCommonTime(new Date());
		var todayStart = time.todayStart;
		var todayEnd = time.todayEnd;
		//昨日开始时间 = 今日开始时间减86400000（24小时）
		// var last_StartTime = todayStart;
		// var last_EndTime = todayEnd;
		var last_StartTime = todayStart - 86400000
		var last_EndTime = todayStart - 1 //昨日结束时间
		var yesterday = vk.pubfn.timeFormat(last_StartTime, "yyyy-MM-dd");
		let copyright = await db.collection('uni-id-users').where({
			role: _.in(["copyright"]),
			isComputed: 0
		}).limit(30).get()
		console.log("本次查询的机构数量=", copyright.data.length);
		//当存在未计算的版权方账号时，才执行以下逻辑
		if (copyright.data.length > 0) {
			let batchRun_copyright = await vk.pubfn.batchRun({
				// 批量执行函数
				main: async (item, index) => {
					await vk.pubfn.sleep((Math.floor(Math.random() * (3 - 0)) + 0) * 100);
					await vk.callFunction({
						name: "hedian",
						url: 'admin/auto_run/pub/compute_copyright_data',
						data: {
							item,
							todayStart,
							todayEnd,
							last_StartTime,
							last_EndTime,
							yesterday
						}
					});
					return {
						code: 0,
						index
					}
				},
				concurrency: 5, // 最大并发量，如果设置为1，则会按顺序执行
				data: copyright.data // 数据源，这些数据会依次跑一遍main函数，相当于for循环里的数组
			});
		} else {
			console.log("不存在版权方的机构账号");
		}
		//计算版权方佣金结束==============================



		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}